package com.bdqn.business.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.base.BaseService;
import com.bdqn.business.system.mapper.DictionariesMapper;
import com.bdqn.entity.system.Dictionaries;
import com.bdqn.response.PageResult;
import com.bdqn.response.Result;
import com.bdqn.response.ResultCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service
@Transactional
public class DictionariesService extends BaseService {

    @Autowired
    private DictionariesMapper dictionariesMapper;

    public Result getDictionariesList(Map<String, Object> map) {

        Object page = map.get("page");
        Object size = map.get("size");
        Object code = map.get("code");

        QueryWrapper<Dictionaries> queryWrapper = new QueryWrapper<>();

        if(code != null && !"".equals(code.toString())) queryWrapper.eq("code",code.toString());

        queryWrapper.orderByDesc("code");

        IPage<Dictionaries> iPage = null;

        if( page == null && size == null ) {
           iPage = new Page<>(1,5000);
        } else {
            iPage  = new Page<>(Integer.parseInt(page.toString()),Integer.parseInt(size.toString()));
        }

        IPage<Dictionaries> result = dictionariesMapper.selectPage(iPage, queryWrapper);

        return new Result(ResultCode.SUCCESS,new PageResult<Dictionaries>(result.getTotal(),result.getRecords()));
    }

    @CachePut(cacheNames = "dictionaries",key = "#dictionaries.id")
    public Result save(Dictionaries dictionaries) {
        dictionaries.setCreateTime(new Date());
        dictionaries.setModifyId(currentUser().getId());
        dictionaries.setModifyUser(currentUser().getNickName());
        dictionaries.setModifyTime(new Date());
        dictionariesMapper.insert(dictionaries);
        return new Result(ResultCode.SUCCESS,dictionaries);
    }

    @CachePut(cacheNames = "dictionaries",key = "#dictionaries.id")
    public Result update(Dictionaries dictionaries) {
        Dictionaries target = dictionariesMapper.selectById(dictionaries.getId());
        BeanUtils.copyProperties(dictionaries,target);
        target.setModifyId(currentUser().getId());
        target.setModifyUser(currentUser().getNickName());
        target.setModifyTime(new Date());
        dictionariesMapper.updateById(target);
        return new Result(ResultCode.SUCCESS,target);
    }

}
